package com.hikeen.launcherx.ui;




import static com.hikeen.launcherx.utils.Constant.HOTSPOTSTATE;
import static com.hikeen.launcherx.utils.Constant.RSSI;
import static com.hikeen.launcherx.utils.Constant.USBSTATE;
import static com.hikeen.launcherx.utils.Constant.WIFIAP_ACTION;
import static com.hikeen.launcherx.utils.Constant.WIFISTATE;
import static com.hikeen.launcherx.utils.Constant.WIRESTATE;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Point;
import android.media.tv.TvContract;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.hikeen.launcherx.FragmentChangeAdapter;
import com.hikeen.launcherx.OneFramgent;
import com.hikeen.launcherx.ThreeFramgent;
import com.hikeen.launcherx.TwoFramgent;
import com.hikeen.launcherx.ViewPagerIndicator;
import com.hikeen.launcherx.bean.AppInfoss;
import com.hikeen.launcherx.floatwindow.Constant;
import com.hikeen.launcherx.floatwindow.LRWindowManagers;
import com.hikeen.launcherx.floatwindow.MainService;
import com.hikeen.launcherx.functions.hotspot.HotSpotStateReceiver;
import com.hikeen.launcherx.functions.hotspot.OnHotSpotStateListener;
import com.hikeen.launcherx.functions.usb.OnUsbStateListener;
import com.hikeen.launcherx.functions.usb.UsbBroadcastReceiver;
import com.hikeen.launcherx.functions.wifi.WIFIState;
import com.hikeen.launcherx.functions.wifi.WIFIUtils;
import com.hikeen.launcherx.functions.wifi.WifiBroadCastReceiver;
import com.hikeen.launcherx.interfaces.MainListener;
import com.hikeen.launcherx.receiver.AppJTReceiver;
import com.hikeen.launcherx.utils.AnimationUtil;
import com.hikeen.launcherx.utils.ChannelUtils;
import com.hikeen.launcherx.utils.FileImageUtils;
import com.hikeen.launcherx.utils.FloatingDraftButton;
import com.hikeen.launcherx.utils.GsonUtils;
import com.hikeen.launcherx.utils.SPUtils;
import com.hjq.language.MultiLanguages;
import com.hikeen.launcherx.R;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * MainActivity优化
 */
public class MainActivity3 extends FragmentActivity implements View.OnClickListener, MainListener
        , OnUsbStateListener, OnHotSpotStateListener {
    private static String TAG = "MAIN-LAUNCHER";
    public static int lastPage = -1;

    private FragmentChangeAdapter fadapter;
    private List<Fragment> flist;//声明一个存放Fragment的List
    private ViewPager viewpager;
    private ViewPagerIndicator viewPagerIndicator;
    private ImageView ivLeft;
    private ImageView ivRight;
    private Intent intent;
    private LinearLayout ll_bottom_tab1;
    private LinearLayout ll_bottom_tab2;
    private LinearLayout ll_bottom_tab3;
    private LinearLayout ll_bottom_tab4;
    private LinearLayout ll_bottom_tab5;
    private LinearLayout ll_bottom_tab6;
    private LinearLayout ll_bottom_tab7;
    FloatingDraftButton floatingDraftButton;
    FloatingActionButton liveness;
    FloatingActionButton floatingActionButton2;
    FloatingActionButton floatingActionButton3;
    FloatingActionButton floatingActionButton4;
    private AppJTReceiver mMyInstallReceiver;
    public static ThreeFramgent threeFramgent;
    public static TwoFramgent twoFramgent;
    public static OneFramgent oneFramgent;
    public static int postionll = -1;


    public ServiceConnection mServiceConnection = new MServiceConnection();
    private MainService mService;
    public ImageView mWIFIImageButton;
    public ImageView mWIREImageButton;
    public ImageView mHOTSPOTImageButton;
    public ImageView mUSBImageButton;

    private void openServices() {
        try {
            if (!serviceIsRunning("com.jiuhong.mytvapplication.ui.MainActivity3")) {
                Intent intent =
                        new Intent(MainActivity3.this, MainService.class);
                bindService(intent, mServiceConnection,
                        Context.BIND_AUTO_CREATE);
            }
//            Intent serviceIntent = new Intent();
//            ComponentName component = new ComponentName("com.jiuhong.mytvapplication", "com.jiuhong.mytvapplication.floatwindow.MyRightService");
//            serviceIntent.setComponent(component);
//            startService(serviceIntent);
//
//            Intent serviceIntent2 = new Intent();
//            ComponentName component2 = new ComponentName("com.jiuhong.mytvapplication", "com.jiuhong.mytvapplication.floatwindow.MyAccessibilityService");
//            serviceIntent2.setComponent(component2);
//            startService(serviceIntent2);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate: main-oncreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        openServices();
        openSidebar();
        verifyStoragePermissions(MainActivity3.this);

        initView();
        initPager();

        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {

                initFloatView();
                initReceiver();
            }
        });
        HotSpotStateReceiver.setHotSpotStateListener(this);
        UsbBroadcastReceiver.setmUsbListener(this);
    }

    private void initReceiver() {
        //动态注册监听安装卸载广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addDataScheme("package");
        mMyInstallReceiver = new AppJTReceiver();
        registerReceiver(mMyInstallReceiver, intentFilter);

        //热点
        HotSpotStateReceiver hotSpotStateReceiver = new HotSpotStateReceiver();
        IntentFilter hotspotFilter = new IntentFilter(WIFIAP_ACTION);
        registerReceiver(hotSpotStateReceiver, hotspotFilter);

        //usb
        UsbBroadcastReceiver usbBroadcastReceiver = new UsbBroadcastReceiver();
        IntentFilter usbFilter = new IntentFilter();
        usbFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        usbFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        usbFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        usbFilter.addDataScheme("file");
        registerReceiver(usbBroadcastReceiver, usbFilter, "android.permission.READ_EXTERNAL_STORAGE", null);


        //wifi
        WifiBroadCastReceiver wifiBroadCastReceiver = new WifiBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(wifiBroadCastReceiver, filter);


        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(BtStatusReceiver, mIntentFilter);
    }

    public BroadcastReceiver BtStatusReceiver = new BroadcastReceiver() // receive broadcast that BT Adapter status change
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                Log.d("Battery", "" + intent.getIntExtra("plugged", 0));
//                Toast text = Toast.makeText(context, "ACTION_USB_DEVICE_ATTACHED" + intent.getIntExtra("plugged", 0), Toast.LENGTH_LONG);
//                text.show();
                Message message = Message.obtain();
                message.what = USBSTATE;
                if (intent.getIntExtra("plugged", 0) == 0) {
                    message.obj = false;
                } else {
                    message.obj = true;
                }
                handler.sendMessage(message);
            }
        }
    };

    public void initFloatView() {
        floatingDraftButton = findViewById(R.id.floatingActionButton);

        liveness = findViewById(R.id.floatingActionButton_liveness);

        floatingActionButton2 = findViewById(R.id.floatingActionButton_2);

        floatingActionButton3 = findViewById(R.id.floatingActionButton_3);

        floatingActionButton4 = findViewById(R.id.floatingActionButton_4);

//         floatingActionButton5 = findViewById(R.id.floatingActionButton_5);

        floatingDraftButton.registerButton(liveness);
        floatingDraftButton.registerButton(floatingActionButton2);
        floatingDraftButton.registerButton(floatingActionButton3);
        floatingDraftButton.registerButton(floatingActionButton4);
//        floatingDraftButton.registerButton(floatingActionButton5);

        floatingDraftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                //弹出动态Button
                AnimationUtil.slideButtons(MainActivity3.this, floatingDraftButton);
            }
        });
        //标注
        liveness.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭动态Button
                AnimationUtil.slideButtons(MainActivity3.this, floatingDraftButton);
                Intent mIntent = new Intent();
                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName component = new ComponentName("com.hikeen.mark", "com.hikeen.mark.MainActivity");
                mIntent.setComponent(component);
                startActivity(mIntent);
            }
        });
        //截屏
        floatingActionButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭动态Button
                AnimationUtil.slideButtons(MainActivity3.this, floatingDraftButton);
                Intent intent = new Intent();
                ComponentName components = new ComponentName("com.hikeen.sidebar", "com.hikeen.sidebar.common.CallService");
                intent.setComponent(components);
                intent.putExtra("key", "screenapp_start");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startService(intent);
            }
        });
        //返回
        floatingActionButton3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭动态Button
                AnimationUtil.slideButtons(MainActivity3.this, floatingDraftButton);
                if (viewpager != null) {

                    viewpager.setCurrentItem(1);
                }
            }
        });
        //主页
        floatingActionButton4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭动态Button
                AnimationUtil.slideButtons(MainActivity3.this, floatingDraftButton);
                if (viewpager != null) {

                    viewpager.setCurrentItem(1);
                }
            }
        });
    }

    private void initView() {

        viewpager = (ViewPager) findViewById(R.id.viewpager);
        viewPagerIndicator = findViewById(R.id.view_page_indicator);

        ivLeft = findViewById(R.id.iv_left);
        ivRight = findViewById(R.id.iv_right);

        ll_bottom_tab1 = findViewById(R.id.ll_bottom_tab1);
        ll_bottom_tab2 = findViewById(R.id.ll_bottom_tab2);
        ll_bottom_tab3 = findViewById(R.id.ll_bottom_tab3);
        ll_bottom_tab4 = findViewById(R.id.ll_bottom_tab4);
        ll_bottom_tab5 = findViewById(R.id.ll_bottom_tab5);
        ll_bottom_tab6 = findViewById(R.id.ll_bottom_tab6);
        ll_bottom_tab7 = findViewById(R.id.ll_bottom_tab7);

        ll_bottom_tab1.setOnClickListener(this);
        ll_bottom_tab2.setOnClickListener(this);
        ll_bottom_tab3.setOnClickListener(this);
        ll_bottom_tab4.setOnClickListener(this);
        ll_bottom_tab5.setOnClickListener(this);
        ll_bottom_tab6.setOnClickListener(this);
        ll_bottom_tab7.setOnClickListener(this);

        MyRightService.setMainListener(this);
        LRWindowManagers.setMainListener(this);
        MyAccessibilityService.setMainListener(this);

        mWIFIImageButton = findViewById(R.id.wifi);
        mWIREImageButton = findViewById(R.id.wire);
        mHOTSPOTImageButton = findViewById(R.id.hotspot);
        mUSBImageButton = findViewById(R.id.usb);

        mWIFIImageButton.setSelected(WIFIUtils.isWiFiActive());
        WIFIUtils.getInstance().registerWIFIStateReceiver(MainActivity3.this);
        initWifi();

    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RSSI:
                    mWIFIImageButton.setImageResource(WIFIState.getInstance().getICON());
                    break;

                case WIFISTATE:
                    mWIFIImageButton.setImageResource(WIFIState.getInstance().getICON());
                    mWIFIImageButton.setSelected((boolean) msg.obj);
                    break;
                case WIRESTATE:
                    mWIREImageButton.setSelected((boolean) msg.obj);
                    break;
                case USBSTATE:
                    mUSBImageButton.setSelected((boolean) msg.obj);
                    break;
                case HOTSPOTSTATE:
                    mHOTSPOTImageButton.setSelected((boolean) msg.obj);
                    break;
            }
        }
    };
    int level = 0;

    private void initWifi() {
        Log.d(TAG, "initWifi: ");

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                    level = ((WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE)).getConnectionInfo().getRssi();
                    int strength = (int) WifiManager.calculateSignalLevel(level, 100);
                    Log.d(TAG, "run: strength " + strength);
                    WIFIState.getInstance().setWIFIRSSI(strength);
                    Message message = handler.obtainMessage();
                    message.what = RSSI;
                    message.arg1 = (int) strength;
                    handler.sendMessage(message);

                    Message message2 = Message.obtain();
                    message2.what = WIRESTATE;
                    message2.obj = isNetworkEnabled();
                    handler.sendMessage(message2);
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private boolean isNetworkEnabled() {
        ConnectivityManager connManager = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager
                .getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        return networkInfo.isConnected();
    }

    private void initPager() {
        flist = new ArrayList<>();//这里如果不写的话,就没有存放Fragment的list了
        //是会报错的
        //添加Fragment
        threeFramgent = new ThreeFramgent();
        twoFramgent = new TwoFramgent();
        oneFramgent = new OneFramgent();
        flist.add(oneFramgent);
        flist.add(twoFramgent);
        flist.add(threeFramgent);
        fadapter = new FragmentChangeAdapter(getSupportFragmentManager(), flist);
        viewpager.setAdapter(fadapter);
        viewPagerIndicator.setCirclerCount(flist.size());
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //positionOffset 表示距离 position的偏移量有多少
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d(TAG, "onPageScrolled: ");
                viewPagerIndicator.setPositionOffset(position, positionOffset);
                if (positionOffset == 0) {
                    viewPagerIndicator.setSelectPosition(position);
                    lastPage = position;
                }
            }

            @Override
            public void onPageSelected(int position) {
                Log.d(TAG, "onPageSelected: 313");
                if (position == 0) {
                    lastPage = position;
                    oneFramgent.chushihua();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.d(TAG, "onPageScrollStateChanged: ");
            }
        });

        viewpager.setCurrentItem(1);
//        viewpager.setOffscreenPageLimit(3);//防止viewpager加载fragment不出的数据
    }

    private void openSidebar() {
        try {

            Intent serviceIntent3 = new Intent();
            ComponentName component3 = new ComponentName("com.hikeen.sidebar", "com.hikeen.sidebar.common.CallService");
            serviceIntent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            serviceIntent3.setComponent(component3);
            serviceIntent3.putExtra("key", "hide");
            startService(serviceIntent3);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy: ");
        unbindService(mServiceConnection);
        WIFIUtils.getInstance().unregisterWiFiStateReceiver(getApplicationContext());
        super.onDestroy();
        //活动onDestroy方法取消注册
        unregisterReceiver(mMyInstallReceiver);
        Log.v(TAG, " onDestroy 1111111111111111111111111");


    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart: ");
        super.onStart();
//        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
//            EventBus.getDefault().register(this);
//        }
    }

    @Override
    public void onStop() {
        super.onStop();

        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_bottom_tab1:
                LRWindowManagers.getInstance().openwinds();
                break;
            case R.id.ll_bottom_tab2: //跳转OPS
//                if (viewpager != null) {
//                    viewpager.setCurrentItem(1);
//                }
                ChannelUtils.startTvWithChannel(getApplicationContext(), TvContract.buildChannelUriForPassthroughInput(Constant.SOURCE_HDMI3));
                break;
            case R.id.ll_bottom_tab3:
                if (viewpager != null) {
                    viewpager.setCurrentItem(0);
                }
                break;
            case R.id.ll_bottom_tab4:
                if (viewpager != null) {
                    viewpager.setCurrentItem(2);
                }
                break;
            case R.id.ll_bottom_tab5:

                MainActivity3.isShowOne = true;
                intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("http://www.baidu.com");
                intent.setData(content_url);
                intent.setClassName("com.android.chrome", "com.google.android.apps.chrome.Main");
                startActivity(intent);

                saveAppClick("com.android.chrome");
                break;
            case R.id.ll_bottom_tab6:
                MainActivity3.isShowOne = true;
                intent = getPackageManager().getLaunchIntentForPackage("com.android.setting3399");
                startActivity(intent);
                saveAppClick("com.android.setting3399");
                break;
            case R.id.ll_bottom_tab7:
                Intent intent = new Intent();
                ComponentName components = new ComponentName("com.hikeen.sidebar", "com.hikeen.sidebar.common.CallService");
                intent.setComponent(components);
                intent.putExtra("key", "lockapp_start");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startService(intent);
                break;

        }
    }

    public static boolean isShowOne = false;

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume: ");
        super.onResume();
        initList();
//        postionll = getIntent().getIntExtra("postion", -1);
        postionll = lastPage;
        if (postionll >= 0) {
            if (viewpager != null) {

                viewpager.setCurrentItem(postionll);
            }

        } else {
            if (viewpager != null) {

                viewpager.setCurrentItem(1);
            }
        }
//        initView();
//        initPager();
    }

    private void saveAppClick(String pack) {
        //这里通过包名来获取app名
        String name = "";
        PackageInfo packageInfo = null;
        PackageManager packageManager = getApplicationContext().getPackageManager();
        try {
            packageInfo = packageManager.getPackageInfo(pack, PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        name = packageInfo.applicationInfo.loadLabel(packageManager).toString();
        String finalName = name;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000); // 休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String s = FileImageUtils.savefilePath(MainActivity3.this, finalName);
                File filePic = new File(s);
                filePic.getParentFile().mkdirs();
                screenShotByShell(s);
            }
        }).start();
        //保存当前打开的APP  到第一条
        String savelist = SPUtils.getString("savelist", "");
        List<AppInfoss> saveL = new ArrayList<>();
        if (TextUtils.isEmpty(savelist)) {
            AppInfoss appInfoss = new AppInfoss();
            appInfoss.setAppName(name);
            appInfoss.setPackageName(pack);
            saveL.add(appInfoss);
        } else {
            List<AppInfoss> appInfosses = GsonUtils.getPersons(savelist, AppInfoss.class);
            int index = -1;
            for (int i = 0; i < appInfosses.size(); i++) {
                if (name.equals(appInfosses.get(i).getAppName()) &&
                        pack.equals(appInfosses.get(i).getPackageName())) {
                    index = i;
                }
            }
            if (index >= 0) {
                appInfosses.remove(index);
            }
            AppInfoss appInfoss = new AppInfoss();
            appInfoss.setAppName(name);
            appInfoss.setPackageName(pack);
            if (appInfosses.size() > 7) {
                appInfosses.remove(appInfosses.size() - 1);
                appInfosses.add(0, appInfoss);
            } else {
                appInfosses.add(0, appInfoss);
            }
            saveL.addAll(appInfosses);
        }
        String s = new Gson().toJson(saveL);
        Log.e("appinfo", "onClick: " + s);
        SPUtils.putString("savelist", s);
    }

    //    三、使用screencap的adb命令
//
//    命令行是这样的：adb shell screencap -p file_path
//
//    在代码中执行，就不用adb shell，直接screencap -p file_path，调用Runtime的进程来执行：
//
    public void screenShotByShell(String filePath) {
        String shotCmd = "screencap -p " + filePath + " \n";
        try {
            Runtime.getRuntime().exec(shotCmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }


    @Override
    protected void attachBaseContext(Context newBase) {
        // 绑定语种
        super.attachBaseContext(MultiLanguages.attach(newBase));
    }


    @Override
    public void onBackPressed() {

    }

    @Override
    public void recent() {
        Log.d(TAG, "recent: 0");
        lastPage = 0;
        viewpager.setCurrentItem(lastPage);
    }

    @Override
    public void reset() {
        Log.d(TAG, "reset: 1");
        lastPage = 1;
        viewpager.setCurrentItem(lastPage);
    }

    @Override
    public void usbOpen() {
        mUSBImageButton.setSelected(true);
//        mUSBImageButton.setBackground(getDrawable(R.drawable.ic_wifi_2));
    }

    @Override
    public void usbClose() {
        mUSBImageButton.setSelected(false);
//        mUSBImageButton.setBackground(getDrawable(R.drawable.ic_wifi_1));
    }

    @Override
    public void onStateEnable() {
        mHOTSPOTImageButton.setSelected(true);
//        mHOTSPOTImageButton.setBackground(getDrawable(R.drawable.ic_wifi_2));
    }

    @Override
    public void onStateDisable() {
        mHOTSPOTImageButton.setSelected(false);
//        mHOTSPOTImageButton.setBackground(getDrawable(R.drawable.ic_wifi_1));
    }

    @Override
    public void onOpening() {

    }

    @Override
    public void onCloseing() {

    }

    class MServiceConnection implements ServiceConnection {
        //这个方法里面那个service
        //就是服务类里面的onBind()方法所返回的IBinder变量了
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            //还是第二步：将服务类的变量实例化：
            //将IBinder向下转型
            MainService.MyBinder myBinder = (MainService.MyBinder) iBinder;
            //调用公有方法就能获得服务类的实例
            mService = myBinder.getService();
            Log.d(TAG, "连接服务");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "意外断开");
            mService.onBoom();
        }
    }

    /**
     * 判断Service是否在运行
     *
     * @return
     */
    private boolean serviceIsRunning(String name) {
        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(Short.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo info : services) {
            if (info.service.getClassName().equals(name)) {
                return true;
            }
        }
        return false;
    }


    private void initList() {
        File Usbfile = new File("/proc/partitions");
        if (Usbfile.exists()) {
            Log.d(TAG, "initList: A");
            try {
                FileReader file = new FileReader("/proc/partitions");
                BufferedReader br = new BufferedReader(file);
                String strLine = "";
                while ((strLine = br.readLine()) != null) {
                    if (strLine.indexOf("sd") > 0) {
                        Log.d(TAG, "initList: 1");
                        Log.d("DEBUG_XYP", "Udisk insert---------->" +
                                "[" + Thread.currentThread().getStackTrace()[2].getFileName() + "," + Thread.currentThread().getStackTrace()[2].getLineNumber() + "]");

                        break;
                    } else {
                        Log.d(TAG, "initList: 2");
                    }

                }
                br.close();
                file.close();
            } catch (Exception e) {
                Log.d(TAG, "initList: Exception");
                e.printStackTrace();
            }
        } else {
            Log.d(TAG, "initList: B");
        }
    }


    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * Checks if the app has permission to write to device storage
     * <p>
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.d(TAG, "dispatchTouchEvent: Main    " + event.getAction());
        Log.d(TAG, "dispatchTouchEvent: index   " + event.getActionIndex());
        if (event.getActionIndex() >= 4) {
            Log.d(TAG, "dispatchTouchEvent: event.getActionIndex() >= 4");
            Log.d(TAG, "dispatchTouchEvent: " + event.getPointerId(0));
            Log.d(TAG, "dispatchTouchEvent: " + event.getX(0));
            Log.d(TAG, "dispatchTouchEvent: " + event.getY(0));
            Point point1 = new Point((int) event.getX(0), (int) event.getY(0));
            Log.d(TAG, "dispatchTouchEvent----1: " + point1.x + "  " + point1.y);
            Point point2 = new Point((int) event.getX(1), (int) event.getY(1));
            Log.d(TAG, "dispatchTouchEvent----2: " + point2.x + "  " + point2.y);
            Point point3 = new Point((int) event.getX(2), (int) event.getY(2));
            Log.d(TAG, "dispatchTouchEvent----3: " + point3.x + "  " + point3.y);
            Point point4 = new Point((int) event.getX(3), (int) event.getY(3));
            Log.d(TAG, "dispatchTouchEvent----4: " + point4.x + "  " + point4.y);
            Point point5 = new Point((int) event.getX(4), (int) event.getY(4));
            Log.d(TAG, "dispatchTouchEvent----5: " + point5.x + "  " + point5.y);

            List listPoint = new ArrayList();
            listPoint.add(point1);
            listPoint.add(point2);
            listPoint.add(point3);
            listPoint.add(point4);
            listPoint.add(point5);
            Point point = getCenterOfGravityPoint(listPoint);
            Log.d(TAG, "dispatchTouchEvent----0x " + point.x + " y " + point.y);
            Log.d(TAG, "dispatchTouchEvent----********************************************************************************** ");
            floatingDraftButton.reflush(point);
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 获取多边形的中心
     *
     * @param
     * @return
     */
    public static Point getCenterOfGravityPoint(List<Point> mPoints) {

        double w = 0;
        double h = 0;
        for (int i = 0; i < mPoints.size(); i++) {
            w += mPoints.get(i).x;
            h += mPoints.get(i).y;
        }

        return new Point((int) w / 5, (int) h / 5);
    }


    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "onConfigurationChanged: ");
        setContentView(R.layout.activity_main);
        initView();
        initPager();
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {

                initFloatView();
                initReceiver();
            }
        });
        HotSpotStateReceiver.setHotSpotStateListener(this);
        UsbBroadcastReceiver.setmUsbListener(this);
    }
}




